module.exports = function(RED) {
  "use strict";  
  function opiInNode(config){
    RED.nodes.createNode(this,config);
    var node = this;
    node.pin = config.pin;
    node.status({fill:"blue",shape:"dot",text:"starting"});

    const fs = require('fs');
    node.path = `/sys/bus/platform/drivers/xgpio/${node.pin}/state`;
    let oldValue;

    // 初始化
    node.on('input', function(msg) {
        try {
            const reading = parseInt(fs.readFileSync(node.path, 'utf8').trim(), 10);
            if (reading !== oldValue) {
                node.send({ payload: Number(reading) });
                node.status({fill:"green",shape:"dot",text:reading});
                oldValue = reading;
            }
        } catch (error) {
            node.error(`Error reading GPIO ${node.pin}: ${error.message}`);
            node.status({fill:"red",shape:"dot",text:"error"});
        }
    });

    // 定时器定期读取 GPIO 状态
    setInterval(() => {
        node.emit('input', { payload: 'poll' });
    }, 1000); // 每 1 秒读取一次

    this.on('close', function(){
        node.log("Closing node");
    });
  }
  RED.nodes.registerType("opi_in",opiInNode);  
}